import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base_notifier.dart';

// 用户数据模型
class User {
  final int id;
  final String name;
  final String email;

  const User({
    required this.id,
    required this.name,
    required this.email,
  });

  @override
  String toString() => 'User(id: $id, name: $name, email: $email)';
}

// 用户数据 Notifier
class UserNotifier extends BaseNotifier<User> {
  UserNotifier();

  @override
  Future<void> loadData({bool isRefresh = false}) async {
    await executeAsync(
      () => _fetchUser(),
      isRefresh: isRefresh,
    );
  }

  // 模拟网络请求
  Future<User> _fetchUser() async {
    await Future.delayed(const Duration(seconds: 2));

    // 模拟不同的响应情况
    if (DateTime.now().millisecond % 3 == 0) {
      throw Exception('网络请求失败');
    }

    return const User(
      id: 1,
      name: '张三',
      email: 'zhangsan@example.com',
    );
  }

  // 更新用户信息
  Future<void> updateUser(User user) async {
    await executeAsync(
      () => _updateUser(user),
      keepDataOnError: true, // 出错时保持原有数据
    );
  }

  Future<User> _updateUser(User user) async {
    await Future.delayed(const Duration(seconds: 1));
    return user;
  }
}

// Provider 定义
final userProvider = NotifierProvider<UserNotifier, BaseState<User>>(() {
  return UserNotifier();
});

// 自动加载用户数据的 Provider
final userAutoLoadProvider = NotifierProvider<UserAutoLoadNotifier, BaseState<User>>(() {
  return UserAutoLoadNotifier();
});

class UserAutoLoadNotifier extends BaseNotifier<User> {
  @override
  BaseState<User> build() {
    // 构建时自动加载数据
    Future.microtask(() => loadData());
    return const BaseState();
  }

  @override
  Future<void> loadData({bool isRefresh = false}) async {
    await executeAsync(
      () => _fetchUser(),
      isRefresh: isRefresh,
    );
  }

  Future<User> _fetchUser() async {
    await Future.delayed(const Duration(seconds: 1));
    return const User(
      id: 1,
      name: '李四',
      email: 'lisi@example.com',
    );
  }
}